package com.zym.init.core.filter;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.zym.init.core.auth.service.TokenService;
import com.zym.init.model.bo.LoginUser;
import com.zym.init.core.utils.SecurityUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Date;

/**
 * token过滤器
 * 验证token有效性
 */
@Slf4j
@Component
public class JwtTokenOncePerRequestFilter extends OncePerRequestFilter {

    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain chain) throws ServletException, IOException {
        LoginUser loginUser = tokenService.getLoginUser();
        if (BeanUtil.isNotEmpty(loginUser) && BeanUtil.isEmpty(SecurityUtils.getAuthentication())) {
            Date expireTime = DateUtil.parseDate(loginUser.getExpireTime());
            Date currentTime = new Date();
            boolean isAfter = currentTime.after(expireTime);
            // log.info("用户ID({}) - token是否过期：{}", loginUser.getUserId(), isAfter ? "已过期" : "未过期");
            if (!isAfter) {
                // log.info("用户ID({}) - 刷新用户token有效期", loginUser.getUserId());
                tokenService.refreshToken(loginUser);
            }
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }

}